<template>
  <el-card>
    <div slot="header">
      <span>商品添加</span>
    </div>
    <div class="content">
      <!-- 表格 -->
      <el-form :model="goodsForm" ref="form" size="small" label-width="100px">
        <el-form-item label="商品名称">
          <el-input class="goods-name" v-model="goodsForm.name"></el-input>
        </el-form-item>

        <el-form-item label="商品分类">
          <el-select v-model="goodsForm.category">
            <el-option :value="item.cateName" v-for="item in options" :key="item.cateName">{{ item.cateName }}</el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品价格">
          <el-input-number v-model="goodsForm.price"></el-input-number>
        </el-form-item>

        <el-form-item label="商品图片">
          <el-upload :on-success="handleImgSuccess" class="avatar-uploader" :show-file-list="false" :action="API + '/goods/goods_img_upload'">
            <img v-if="goodsForm.imgUrl" :src="API + goodsForm.imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品描述">
          <el-input rows="7" class="desc" type="textarea" v-model="goodsForm.goodsDesc"></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="submitForm">添加商品</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
import { getGoodsCateName, addGoods } from '@/api/goods'
export default {
  data() {
    return {
      // 图片上传拼接地址
      API: 'http://127.0.0.1:5000',
      goodsForm: {
        name: '',
        category: '',
        price: '',
        imgUrl: '',
        goodsDesc: ''
      },
      options: [] //分类名选项
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      let { data } = await getGoodsCateName()
      this.options = data
    },
    // 商品图片上传
    handleImgSuccess(res) {
      console.log(res)

      if (res.code === 0) {
        this.$message({
          type: 'success',
          message: res.msg
        })
        this.goodsForm.imgUrl = res.imgUrl
      }
    },
    // 提交表单
    async submitForm() {
      console.log('提交')
      // 浅拷贝
      let data = { ...this.goodsForm }
      data.imgUrl = data.imgUrl.substr(23)
      let res = await addGoods(data)
      if (res.data.code === 0) {
        this.$router.push('/goods/goods-list')
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.goods-name {
  width: 194px;
}
.desc {
  width: 300px;
}
</style>
